﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.OleDb;
using DOAN.DO;
using DOAN.BL;

namespace DOAN.Admin
{
    public partial class QL_Cauhoi : System.Web.UI.Page
    {
        string magv="";
        string mamon="";
        public SqlConnection sqlcon = new SqlConnection("Data source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|trac_nghiem.mdf;Integrated Security=True;user Instance=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["quyen"]==null)
                Response.Redirect("LoginAdmin.aspx");
            else
            {
                if ((Session["quyen"].ToString() == "AD") || (Session["quyen"].ToString() == "GV"))
                {
                    if (Session["Tendangnhap"] != null && Session["Tendangnhap"].ToString() != "")
                    {
                        MasterPage mt = this.Master as MasterPage;
                        LinkButton lb = mt.FindControl("LinkButton1") as LinkButton;
                        lb.Visible = false;
                        Label bl = mt.FindControl("lblDnthanhcong") as Label;
                        bl.Visible = true;
                        Label blten = mt.FindControl("lbtendn") as Label;
                        blten.Visible = true;
                        blten.Text = Session["Tendangnhap"].ToString();
                        LinkButton lbDangky = mt.FindControl("lbDangky") as LinkButton;
                        lbDangky.Visible = false;
                        LinkButton lbthoat = mt.FindControl("lbThoat") as LinkButton;
                        lbthoat.Visible = true;
                        Session["MaTK"].ToString();
                    }

                    if (!IsPostBack)
                    {
                        string tentaikhoan = Session["Tendangnhap"].ToString();
                        //string tentaikhoan2 = Session["Tendangnhap"].ToString();
                        //Napmonhoc_themagv(magv);
                        //Napmadokho();
                        Napmonhoc1(tentaikhoan);
                        Napmonhoc2(tentaikhoan);
                        Napmonhoc3(tentaikhoan);
                        Cauhoi_mon_gv();
                        Cauhoi_mon_gv2();
                        //  napCauhoi_mon_gv(mamon, magv);
                        //DS_cauhoi_dapan(mamon);
                    }
                }
                else
                {
                    Response.Redirect("~/Default.aspx");
                }
            }
        }
        private void Napmonhoc1(string tentaikhoan)
        {
            DataTable data = new CT_MonhocBL().GetByUser(tentaikhoan);
            try
            {
                gridCauhoi.DataBind();
                drMonhoc1.DataSource = data;
                drMonhoc1.DataTextField = "Tenmon";
                drMonhoc1.DataValueField = "Mamonhoc";
                drMonhoc1.DataBind();

            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }
        private void Napmonhoc2(string tentaikhoan)
        {

            DataTable data = new CT_MonhocBL().GetByUser(tentaikhoan);
            try
            {
                drMonhoc2.DataSource = data;
                drMonhoc2.DataTextField = "Tenmon";
                drMonhoc2.DataValueField = "Mamonhoc";
                drMonhoc2.DataBind();

            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {

            }
        }
        private void Napmonhoc3(string tentaikhoan)
        {
            DataTable data = new CT_MonhocBL().GetByUser(tentaikhoan);
            try
            {
                drMonhoc3.DataSource = data;
                drMonhoc3.DataTextField = "Mamonhoc";
                drMonhoc3.DataValueField = "Mamonhoc";
                drMonhoc3.DataBind();

            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }
        private void Cauhoi_mon_gv()
        {
            string mamon = drMonhoc1.SelectedValue;
            DataTable dt = new CauhoiBL().GetByMon(mamon); 
            try
            {
                gridCauhoi.DataSource = dt;
                gridCauhoi.DataBind();
                /*for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (Session["Tendangnhap"].ToString() == dt.Rows[i].ItemArray[6].ToString())
                        gridCauhoi.FindControl("img_suach").Visible = true;
                }*/
            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }
        private void Cauhoi_mon_gv2()
        {
            string mamon = drMonhoc1.SelectedValue;
            DataTable dt = new CT_MonhocBL().GetByMon(mamon);
            try
            {
                gridCauhoi2.DataSource = dt;
                gridCauhoi2.DataBind();
                /*for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (Session["Tendangnhap"].ToString() == dt.Rows[i].ItemArray[6].ToString())
                        gridCauhoi.FindControl("img_suach").Visible = true;
                }*/
            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }

        protected void gridCauhoi_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int macauhoi = Convert.ToInt32(e.CommandArgument);
            string mamon = drMonhoc1.SelectedValue;
            string dokho = drDokho.SelectedValue;
            string chuong = drChuong.SelectedValue;
            int result = 0;
            try
            {
                if (e.CommandName == "xoa")
                {
                    result = new CauhoiBL().Delete(new CauhoiDO { Macauhoi = macauhoi });
                    if (result == 0)
                        lblLoi.Text = "Loi xoa";
                    else
                    {
                        lblLoi.Text = "Xoa thanh cong!!";
                        Cauhoi_mon_gv();
                    }
                }
                else
                {
                    if (e.CommandName == "sua")
                    {
                        pnSua.Visible = true;
                        pnThem.Visible = false;
                        Lay_cauhoima(macauhoi);
                        lblLoi.Visible = false;
                        gridCauhoi2.Visible = false;
                    }
                }

            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }
        protected void gridCauhoi2_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int macauhoi = Convert.ToInt32(e.CommandArgument);
            string mamon = drMonhoc1.SelectedValue;
            string dokho = drDokho.SelectedValue;
            string chuong = drChuong.SelectedValue;
            int result = 0;
            try
            {
                if (e.CommandName == "xoa2")
                {
                    result = new CauhoiBL().Delete(new CauhoiDO { Macauhoi = macauhoi });
                    if (result == 0)
                        lblLoi.Text = "Loi xoa";
                    else
                    {
                        lblLoi.Text = "Xoa thanh cong!!";
                        Cauhoi_mon_gv2();
                    }
                }
                else
                {
                    if (e.CommandName == "sua2")
                    {
                        pnSua.Visible = true;
                        pnThem.Visible = false;
                        Lay_cauhoima(macauhoi);
                        lblLoi.Visible = false;
                        gridCauhoi2.Visible = false;
                    }
                }

            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }
        // Lay cau hoi theo ma cau hoi
        private void Lay_cauhoima(int macauhoi)//thuc hien chuc nang bind data 
        {
            CauhoiDO obj = new CauhoiDO();
            try
            {
                obj = new CauhoiBL().Select(new CauhoiDO { Macauhoi = macauhoi });
                txtMacauhoi.Text = obj.Macauhoi.ToString();
                drMonhoc2.SelectedValue = obj.Mamonhoc;
                txtNoidung.Text = obj.Noidung;
                drDokho.SelectedValue = obj.Dokho.ToString();
                drChuong.SelectedValue = obj.Chuong.ToString() ;
                // Truyền image.............................................................................
                //upHinhAnh.FileName = Convert.ToString(mBAL.Hienthi_Cauhoima(macauhoi).Rows[0].ItemArray[5]);
                lblUpanh.Text = obj.Image;
                txtDapanA.Text = obj.DapanA;
                txtDapanB.Text = obj.DapanB;
                txtDapanC.Text = obj.DapanC;
                txtDapanD.Text = obj.DapanD;
                txtDapandung.Text = obj.Phuongandung;
            }

            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }
        protected void gridCauhoi_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //string magvv = magv = Session["MaTK"].ToString();
            string monhoc = drMonhoc1.SelectedValue;
            gridCauhoi.PageIndex = e.NewPageIndex;
            this.Cauhoi_mon_gv();
            lblLoi.Visible = true;
        }
        protected void gridCauhoi2_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //string magvv = magv = Session["MaTK"].ToString();

            string monhoc = drMonhoc1.SelectedValue;
            gridCauhoi2.PageIndex = e.NewPageIndex;
            this.Cauhoi_mon_gv2();
            lblLoi.Visible = true;
        }
        protected void btChon_Click(object sender, EventArgs e)
        {
        }
        protected void imgRe_Click(object sender, ImageClickEventArgs e)
        {
            lblLoi.Visible = false;
            Cauhoi_mon_gv();
            Cauhoi_mon_gv2();
            pnSua.Visible = false;
            pnThem.Visible = false;
            gridCauhoi.Visible = true;
            gridCauhoi2.Visible = false;
        }
        protected void imgThem_Click(object sender, ImageClickEventArgs e)
        {

            pnThem.Visible = true;
            pnSua.Visible = false;
            lblLoi.Visible = false;
            gridCauhoi.Visible = true;
            gridCauhoi2.Visible = false;
        }
        protected void imgDanhsach_cauhoi_Click(object sender, ImageClickEventArgs e)
        {
            Cauhoi_mon_gv();
            gridCauhoi.Visible = true;
            gridCauhoi2.Visible = false;
            lblLoi.Visible = false;
            pnSua.Visible = false;
            pnThem.Visible = false;


        }
        protected void imgDanhsach_cauhoi_dapan_Click(object sender, ImageClickEventArgs e)
        {
            Cauhoi_mon_gv2();
            gridCauhoi.Visible = false;
            gridCauhoi2.Visible = true;
            lblLoi.Visible = false;
            pnSua.Visible = false;
            pnThem.Visible = false;


        }

        protected void imgTimkiem_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void imgImport_Click(object sender, ImageClickEventArgs e)
        {
            pnImport.Visible = true;
            gridCauhoi.Visible = false;
            //gridCauhoi2.Visible = true;
        }
        protected void imgtk_Click(object sender, ImageClickEventArgs e)
        {
            if (txtTimkiem.Text == "")
            {
                lblLoi.Text = "Bạn chưa nhập thông tin tìm kiếm";
            }
            else
            {
                string macauhoi = txtTimkiem.Text;
                Tim_kiem(macauhoi);
                gridCauhoi.Visible = true;
                gridCauhoi2.Visible = false;
            }
        }


        private void Tim_kiem(string tk)
        {
            try
            {
                //int tk = int.Parse(macauhoi);
                gridCauhoi.DataSource = new CauhoiBL().timkiem(tk);
                gridCauhoi.DataBind();

            }
            catch (Exception ee)
            {
                lblLoi.Text = ee.Message;
            }
            finally
            {
            }
        }

        protected void btSua_Click(object sender, EventArgs e)
        {

            CauhoiDO obj = new CauhoiDO();
            int kq = 0;
            obj.Macauhoi = int.Parse(txtMacauhoi.Text.ToString());
            obj.Mamonhoc = drMonhoc2.SelectedValue;
            obj.Chuong = int.Parse(drChuong.SelectedValue.ToString());
            obj.Dokho = int.Parse(drDokho.SelectedValue.ToString());
            string sTenfile2;
            sTenfile2 = upHinhAnh.FileName;
            string image = "";
            if (!upHinhAnh.HasFile)
            {
                image = lblUpanh.Text;
            }
            else
                image = "~/Upload/" + sTenfile2;
            obj.Image = image;
            obj.Noidung = txtNoidung.Text;
            obj.DapanA = txtDapanA.Text;
            obj.DapanB = txtDapanB.Text;
            obj.DapanC = txtDapanC.Text;
            obj.DapanD = txtDapanD.Text;
            obj.Phuongandung = txtDapandung.Text;
            try
            {
                kq = new CauhoiBL().Update(obj);
                if (kq == 0)
                {
                    lblLoi.Visible = true;
                    if(upHinhAnh.HasFile == true)
                        upHinhAnh.SaveAs(MapPath("~/Upload/" + sTenfile2));
                    lblLoi.Text = "Update thanh cong !";
                    pnSua.Visible = false;
                    Cauhoi_mon_gv();
                }
                else
                {
                    lblLoi.Visible = true;
                    lblLoi.Text = "Update khong thanh cong !";
                }
            }
            catch (Exception ex)
            {
                lblLoi.Text = ex.Message;
            }
            finally
            {
            }
        }

        public CauhoiDO init()
        {
            CauhoiDO obj = new CauhoiDO();
            obj.Mamonhoc = drMonhoc3.SelectedValue;
            obj.Chuong = int.Parse(drChuong2.SelectedValue.ToString());
            obj.Dokho = int.Parse(drDokho2.SelectedValue.ToString());
            string image = "~/Upload/" + upHinhanh2.FileName;
            obj.Noidung = txtNoidung2.Text;
            obj.DapanA = txtDapanA2.Text;
            obj.DapanB = txtDapanB2.Text;
            obj.DapanC = txtDapanC2.Text;
            obj.DapanD = txtDapanD2.Text;
            obj.Phuongandung = txtDapandung2.Text;
            return obj;
        }

        protected void btThem_Click(object sender, EventArgs e)
        {
            //Thực hiện chép tập tin lên thư mục Upload
            if(upHinhanh2.HasFile ==true)
                upHinhanh2.SaveAs(MapPath("~/Upload/" + upHinhanh2.FileName));
            int kq = 0;
            try
            {
                kq = new CauhoiBL().Insert(init());
                if (kq > 0)
                {
                    lblLoi.Visible = true;
                    lblLoi.Text = "Them thanh cong !";

                    pnThem.Visible = false;
                    Cauhoi_mon_gv();

                }
                else
                {
                    lblLoi.Text = "Them khong thanh cong !";
                }
            }
            catch (Exception ex)
            {
                lblLoi.Text = ex.Message;
            }
            finally
            {
            }
        }

        protected void btHuy_Click(object sender, EventArgs e)
        {
            pnSua.Visible = false;
            lblLoi.Visible = false;

        }
        protected void btHuy_Click2(object sender, EventArgs e)
        {
            pnThem.Visible = false;
            lblLoi.Visible = false;

        }

        protected void drMonhoc1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string magvv = magv = Session["MaTK"].ToString();
            Cauhoi_mon_gv();
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            string ExcelFilename = FileUpload1.PostedFile.FileName;
            string ExcelFileNameonly = ExcelFilename.Substring(ExcelFilename.LastIndexOf("\\") + 1);
            string FileExt = ExcelFilename.Substring(ExcelFilename.LastIndexOf(".") + 1);
            string Filenamewithoutextn = ExcelFileNameonly.Remove(ExcelFileNameonly.LastIndexOf("."));
            if (FileExt.ToLower() == "xls")
            {
                try
                {
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("Imported Files/") + Filenamewithoutextn + ".xls");
                    string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Imported Files/") + Filenamewithoutextn + ".xls;Extended Properties=Excel 8.0;";

                    OleDbConnection olecon = new OleDbConnection(strConnectionString);

                    int RecordCount = 0;
                    lblMessage.Visible = false;
                    lblError.Visible = false;
                    olecon.Open();
                    OleDbCommand cmd = olecon.CreateCommand();
                    cmd.CommandText = "SELECT * FROM [Sheet1$]";
                    DataSet ds = new DataSet();
                    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                    OleDbDataReader dr = cmd.ExecuteReader();

                    sqlcon.Open();
                    //string deletestr = "delete from importdata";
                    //SqlCommand sqlcmd = new SqlCommand(deletestr, sqlcon);
                    //sqlcmd.ExecuteNonQuery();

                    while (dr.Read())
                    {
                        //db.excutequery("delete from Cauhoi where UserID='" + dr[0] + "'", CommandType.Text);
                        //new CauhoiBL().Delete(new CauhoiDO { Macauhoi = dr[0].ToString() });
                        
                        CauhoiDO obj = new CauhoiDO();
                        obj.Mamonhoc = dr[0].ToString();
                        obj.Noidung = dr[1].ToString();
                        obj.Dokho = int.Parse(dr[2].ToString());
                        obj.Chuong = int.Parse(dr[3].ToString());
                        obj.Image = dr[4].ToString();
                        obj.Video = dr[5].ToString();
                        obj.DapanA = dr[6].ToString();
                        obj.DapanB = dr[7].ToString();
                        obj.DapanC = dr[8].ToString();
                        obj.DapanD = dr[9].ToString();
                        obj.Phuongandung = dr[10].ToString();
                        if (new CauhoiBL().Select2(obj).Rows.Count > 0)
                        {
                            new CauhoiBL().Update(obj);
                        }
                        else
                        {
                            new CauhoiBL().Insert(obj);
                        }
                        
                        //new CauhoiBL().Insert(obj);
                        RecordCount++;
                        lblMessage.Visible = true;
                        lblMessage.Text = " Thực hiện thành công : " + RecordCount.ToString() + " Bản ghi!";
                        Cauhoi_mon_gv2();
                        gridCauhoi2.Visible = true;
                    }
                    dr.Close();
                    olecon.Close();
                    BindGrid();
                    sqlcon.Close();
                }
                catch (Exception ex)
                {
                    lblError.Visible = true;
                    lblError.Text = ex.Message;
                }
            }

        }
        private void BindGrid()
        {
            try
            {
                lblError.Visible = false;
                gridCauhoi2.DataSource = new CauhoiBL().SelectAll();
                gridCauhoi2.DataBind();
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = ex.Message;
            }

        }
    }
}
